<?php


namespace app\cms\model;


use app\cms\community\lib\QueryModel;
use app\community\tool;
use iflow\Response;

class shortLinkModel extends QueryModel
{
    public $table = 'short_link_table';

    public function saveShortUrl(string $url): Response
    {
        $preg = "/http[s]?:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is";
        if(!preg_match($preg, $url)) {
            return message() -> parameter_error('url 地址错误');
        }
        $shortUrl = (new tool()) -> shortUrl($url);

        $exists = $this->where([
            'short_code' => $shortUrl
        ]) -> findOrEmpty();

        if ($exists -> isExists()) return message() -> success('创建成功', $exists -> toArray());
        return $this->createData([
            'short_code' => $shortUrl,
            'url' => $url
        ]);
    }
}